package com.newenergy.wisehome.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.light.Helper.BleDataHelper;
import com.newenergy.light.callback.BleScanCallBack;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.ui.adapter.ScanHEAAdapter;
import com.newenergy.wisehome.ui.widget.LoaddingDialogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.ISupportFragment;

/**
 * Created by kyx on 2018/7/10.
 *
 */

public class ScanHEAFramgment extends BaseFragment implements BleScanCallBack {

    private static String ARG_SCANEHEA = "arg_scanequip";
    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.img_loading)
    ImageView mImgLoading;
    @BindView(R.id.recyclerView)
    EasyRecyclerView mRecyclerView;
    @BindView(R.id.btn_add)
    Button mBtnAdd;
    @BindView(R.id.btn_search_again)
    Button mBtnSearchAgain;



    private Family mFamily;
    private ScanHEAAdapter mAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private DeviceCategory mSaveDevice;
    private Dialog mLoadingDialog;
    private List<String> mDeviceIdList = new ArrayList<>();

    private List<String> deviceCategoryName = new ArrayList<>();
    private int confirType;

    public static ISupportFragment newInstance(Family currFamily) {
        Bundle args = new Bundle();
        args.putParcelable(ARG_SCANEHEA, currFamily);
        ScanHEAFramgment fragment = new ScanHEAFramgment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_scanequip;
    }


    @Override
    public void init(View rootView) {
        startLoadingAnimation();
        mFamily = getArguments().getParcelable(ARG_SCANEHEA);
        mTvPage.setText(R.string.btn_add_hea);
        mBtnAdd.setVisibility(View.GONE);
        mBtnAdd.setBackgroundResource(R.drawable.btn_search);
        initRecycleView();

        mAdvertiserManager.setBleScanCallBack(this);

        confirType=1;
        showPositiveDialog(getString(R.string.remove_then_reset));

    }


    @Override
    public void onResume() {
        super.onResume();
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        List<DeviceCategory> familyDeviceCategorys = deviceCategoryDao.getFamilyDeviceCategorys(mFamily.getFamilyId());

        for (DeviceCategory deviceCategory : familyDeviceCategorys) {
            deviceCategoryName.add(deviceCategory.getName());
        }
    }


    private void initRecycleView() {
        Context context = getContext();
        mAdapter = new ScanHEAAdapter(context);
        mRecyclerView.setAdapter(mAdapter);
        mLinearLayoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mAdapter.setItemOperCallBack(new ScanHEAAdapter.ItemOperCallBack() {
            @Override
            public void notifyAdd(int position) {
                mSaveDevice = mAdapter.getItem(position);
                String data2 = intToHex(mFamily.getSeed()) + numToHexs(mFamily.getFeedback());

                String deviceId = mSaveDevice.getDeviceId();
                String subDeviceId = BleDataHelper.subHexStr(deviceId, 2, 4);//设备ID-UUID
                String groupId;

                DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
                DeviceCategory deviceCategory = deviceCategoryDao.getFamilyHEAByDeviceid(mFamily.getFamilyId(), deviceId);
                if (deviceCategory != null) {
                    groupId = deviceCategory.getGroupId();
                } else {
                    //获取当前组号
                    int count = mFamily.getDeviceCount();
                    count++;
                    if (count > 255) {
                        count = 1;
                    }
                    groupId = intToHex(count);

                    Log.i(TAG, "notifyAdd: count = " + count + "  groupId = " + groupId);
                }

                mSaveDevice.setGroupId(groupId);
                //发送数据进行添加设备
                AppManager.getInstance(mainActivity).commandAdvertiseInNum("05", subDeviceId, groupId, mFamily.getFamilyId(), data2, 73, 4777, 2, "7202", 80);

                //1代表用当前家庭码解密
                mAdvertiserManager.scanType = 1;
                mAdvertiserManager.mSeed = mFamily.getSeed();
                mAdvertiserManager.mFeedBack = mFamily.getFeedback();
                //显示遮罩屏幕，在添加成功以及8秒钟后消失
                mLoadingDialog = LoaddingDialogUtils.createLoadingDialog(mainActivity, getString(R.string.adding));//"正在添加中..."
                mHandler.sendEmptyMessageDelayed(1, 8000);

                mHandler.removeMessages(3);

            }
        });
    }


    private void startLoadingAnimation() {
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.img_animation);
        LinearInterpolator lin = new LinearInterpolator();//设置动画匀速运动
        animation.setInterpolator(lin);
        mImgLoading.startAnimation(animation);
    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_add,R.id.btn_search_again})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();

                break;
            case R.id.tv_back:
                doBack();
                break;

            case R.id.btn_add:
                AppManager.getInstance(mainActivity).commandAdvertiseInNum("F4", "00000000", "00", "00000000", "000000", 73, 4777, 2, "7202", 80);

                break;


            case R.id.btn_search_again:
                AppManager.getInstance(mainActivity).commandAdvertiseInNum("F4", "00000000", "00", "00000000", "000000", 73, 4777, 2, "7202", 80);
                mHandler.sendEmptyMessageDelayed(3, 10000);
                mBtnSearchAgain.setVisibility(View.GONE);
                break;
        }
    }


    @Override
    public void onStop() {
        super.onStop();
    }


    @Override
    protected void confirmOperation() {
        super.confirmOperation();
        if (confirType == 1) {
            mAdvertiserManager.startScan();
            AppManager.getInstance(mainActivity).commandAdvertiseInNum("F4", "00000000", "00", "00000000", "000000", 73, 4777, 2, "7202", 80);
            mHandler.sendEmptyMessageDelayed(3, 10000);
        }
    }


    @Override
    public void foundDevice(String deviceId) {


        if (getContext() == null) {
            return;
        }

        Log.e("LFX", "deviceId===" + deviceId);

        String deviceType = BleDataHelper.subHexStr(deviceId, 0, 1);
        int category = Integer.parseInt(deviceType, 16);

        String model = BleDataHelper.subHexStr(deviceId, 0, 4);

        if (mDeviceIdList != null) {
            if (mDeviceIdList.size() > 0) {
                for (String hadDeviceId : mDeviceIdList) {
                    if (hadDeviceId.equalsIgnoreCase(deviceId)) {
                        return;
                    }
                }
            }

            mDeviceIdList.add(deviceId);
        }

        String familyId = mFamily.getFamilyId();

        DeviceCategoryDao deviceDao = new DeviceCategoryDao(getContext());
        DeviceCategory deviceCategory = deviceDao.getFamilyHEAByDeviceid(familyId, deviceId);
        if (deviceCategory != null) {//数据库已保存过该设备
            mAdapter.add(deviceCategory);
            mAdvertiserManager.familyId = familyId;
            return;
        }
        //创建新家电
        if (category == 2) {//"风扇"

            String name = getNewName(getString(R.string.name_fan), deviceCategoryName);
            deviceCategoryName.add(name);
            deviceCategory = new DeviceCategory(familyId, category, "01", name, "btn_fan", deviceId, model);

        } else if (category == 3) {//风扇灯

            String name = getNewName(getString(R.string.name_fanLamp), deviceCategoryName);
            deviceCategoryName.add(name);
            deviceCategory = new DeviceCategory(familyId, category, "01", name, "btn_fanlamp", deviceId, model);

        } else if (category == 5) {//浴霸

            String name = getNewName(getString(R.string.name_bathheater), deviceCategoryName);
            deviceCategoryName.add(name);
            deviceCategory = new DeviceCategory(familyId, category, "01", name, "btn_batnheater", deviceId, model);

        }else if (category == 11) {//智能开关

            String name = getNewName(getString(R.string.name_smart_switch), deviceCategoryName);
            deviceCategoryName.add(name);
            deviceCategory = new DeviceCategory(familyId, category, "01", name, "btn_smart_switch", deviceId, model);

        } else if (category == 13) {//加湿器

            String name = getNewName(getString(R.string.name_humidifier), deviceCategoryName);
            deviceCategoryName.add(name);
            deviceCategory = new DeviceCategory(familyId, category, "01", name, "btn_humidifier", deviceId, model);

        }
        if (deviceCategory != null) {
            mAdapter.add(deviceCategory);
        }


        mAdvertiserManager.familyId = familyId;
    }


    @Override
    public void saveDevice(String groupId) {
        Log.i(TAG, "saveDevice: ");
        if (getContext() == null) {
            return;
        }

        if (mSaveDevice == null) {
            return;
        }

        if (!mSaveDevice.getGroupId().equalsIgnoreCase(groupId)) {
            return;
        }
        mAdvertiserManager.scanType = 0;
        DeviceCategory deviceCategory = getDeviceCategoryFromDB();

        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext().getApplicationContext());
        if (deviceCategory != null) {
            deviceCategory.setGroupId(groupId);
            deviceCategoryDao.updateDeviceCategory(deviceCategory);
            Log.e("LFX", "保存的deviceCategory===" + deviceCategory.toString());
            deviceCategory = getDeviceCategoryFromAdapter();
            if (deviceCategory != null) {
                mAdapter.remove(deviceCategory);//数据库有优先删除列表
                showDialog(getString(R.string.continue_to_use));//已添加过该设备！请继续使用！
                mHandler.sendEmptyMessageDelayed(2, 1000);
            }
        } else {
            deviceCategory = getDeviceCategoryFromAdapter();
            if (deviceCategory != null) {
                deviceCategory.setGroupId(groupId);
                int count = strToInt(groupId);
                mFamily.setDeviceCount(count);

                deviceCategoryDao.add(deviceCategory);

                FamilyDao familyDao = new FamilyDao(getContext());
                familyDao.updateFamily(mFamily);
                mAdapter.remove(deviceCategory);//数据库有优先删除列表
                showDialog(getString(R.string.add) + deviceCategory.getName() + getString(R.string.success));
                mHandler.sendEmptyMessageDelayed(2, 1000);
                Log.e("LFX", "保存的deviceCategory===2" + deviceCategory.toString());

            }

        }

        LoaddingDialogUtils.closeDialog(mLoadingDialog);
        mHandler.removeMessages(1);
        mSaveDevice = null;
    }

    @Override
    public void deleteDevice(String deviceId) {

    }


    public DeviceCategory getDeviceCategoryFromAdapter() {
        if (mAdapter == null) return null;
        List<DeviceCategory> lights = mAdapter.getAllData();
        if (mSaveDevice != null) {
            for (DeviceCategory deviceCategory : lights) {
                if (mSaveDevice.getDeviceId().equals(deviceCategory.getDeviceId())) {
                    return deviceCategory;
                }
            }
        }
        return null;
    }


    public DeviceCategory getDeviceCategoryFromDB() {
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        List<DeviceCategory> allDeviceCategory = deviceCategoryDao.getFamilyDeviceCategorys(mFamily.getFamilyId());
        if (mSaveDevice != null) {
            String deviceId = mSaveDevice.getDeviceId();
            for (DeviceCategory deviceCategory : allDeviceCategory) {
                if (deviceId.equals(deviceCategory.getDeviceId())) {
                    return deviceCategory;
                }
            }
        }

        return null;
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    LoaddingDialogUtils.closeDialog(mLoadingDialog);
                    if (mHandler != null) {
                        showDialog(getString(R.string.timeout_to_try));
                        mHandler.sendEmptyMessageDelayed(2, 1000);
                        mAdvertiserManager.scanType = 0;
                    }
                    break;
                case 2:
                    dissDialog();
                    mHandler.removeMessages(2);
                    mBtnSearchAgain.setVisibility(View.VISIBLE);

                    break;

                case 3:
                    mBtnSearchAgain.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        mAdvertiserManager.stopScan();
        mAdvertiserManager.scanType = 0;
        mDeviceIdList.clear();
        mDeviceIdList = null;
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        mSaveDevice = null;
        mImgLoading.clearAnimation();
        mAdvertiserManager.setBleScanCallBack(null);
    }

}
